package org.example.ding.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 错误页面控制器
 */
@Controller
public class ErrorController implements org.springframework.boot.web.servlet.error.ErrorController {

    @RequestMapping("/error")
    public String handleError(HttpServletRequest request, Model model) {
        Integer statusCode = (Integer) request.getAttribute("jakarta.servlet.error.status_code");
        String errorMessage = (String) request.getAttribute("jakarta.servlet.error.message");
        String requestUri = (String) request.getAttribute("jakarta.servlet.error.request_uri");
        
        model.addAttribute("statusCode", statusCode);
        model.addAttribute("errorMessage", errorMessage);
        model.addAttribute("requestUri", requestUri);
        
        // 根据状态码返回不同的错误页面
        if (statusCode != null) {
            switch (statusCode) {
                case 404:
                    model.addAttribute("title", "页面未找到");
                    model.addAttribute("description", "抱歉，您访问的页面不存在。");
                    break;
                case 403:
                    model.addAttribute("title", "访问被拒绝");
                    model.addAttribute("description", "抱歉，您没有权限访问此页面。");
                    break;
                case 500:
                    model.addAttribute("title", "服务器内部错误");
                    model.addAttribute("description", "抱歉，服务器遇到了一个错误。");
                    break;
                default:
                    model.addAttribute("title", "发生错误");
                    model.addAttribute("description", "抱歉，发生了一个意外错误。");
                    break;
            }
        } else {
            model.addAttribute("title", "发生错误");
            model.addAttribute("description", "抱歉，发生了一个意外错误。");
        }
        
        return "error";
    }
}
